import * as koffi from 'koffi'

export class FFILibrary {
  private lib: koffi.IKoffiLib
  ffi_getData: any
  ffi_freeArray: any
  constructor(private libPath: string) {
    this.libPath = libPath
    try {
      this.lib = koffi.load(this.libPath)
      koffi.struct('FFIData', {
        data: 'void*',
        size: 'size_t'
      });
      this.ffi_getData = this.lib.func('FFIData ffi_getData(const char*)');
      this.ffi_freeArray = this.lib.func('void ffi_freeArray(void*)');
    } catch (error: any) {
      throw new Error(error.message)
    }
  }

  public getData() {
    const { ffi_getData, ffi_freeArray } = this
    const options = {
      name: 'lgw'
    }
    const result = ffi_getData(JSON.stringify(options));
    const uint8Array = koffi.decode(result.data, 'uint8', result.size);
    const str = Buffer.from(uint8Array).toString('utf8');
    ffi_freeArray(koffi.address(result.data))
    return str;
  }

  public add(a: number, b: number): number {
    return this.lib.func('int add(int a, int b)')(a, b)
  }
}
